package com.maxtech.common.gps;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.maxtech.basestation.CellIDInfo;

import android.app.Activity;
import android.content.Context;
import android.net.Proxy;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

public abstract class IAddressTask {

	private static final String TAG = null;
	protected Activity context;
	ArrayList<CellIDInfo> CellID = new ArrayList<CellIDInfo>();
	
	public IAddressTask(Activity context) {
		this.context = context;
	}
	
	public abstract HttpResponse execute(JSONObject params) throws Exception;
	
	public MLocation doWifiPost() throws Exception {
		return transResponse(execute(doWifi()));
	}
	
	public MLocation doApnPost() throws Exception  {
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		int type = tm.getNetworkType();
		//在中国，移动的2G是EGDE，联通的2G为GPRS，电信的2G为CDMA，电信的3G为EVDO 
		//String OperatorName = tm.getNetworkOperatorName(); 
		//中国电信为CTC
		//NETWORK_TYPE_EVDO_A是中国电信3G的getNetworkType
		//NETWORK_TYPE_CDMA电信2G是CDMA
		if (type == TelephonyManager.NETWORK_TYPE_EVDO_A || type == TelephonyManager.NETWORK_TYPE_CDMA || type ==TelephonyManager.NETWORK_TYPE_1xRTT)
		{
			CdmaCellLocation location = (CdmaCellLocation) tm.getCellLocation();
			int cellIDs = location.getBaseStationId();
			int networkID = location.getNetworkId();
			StringBuilder nsb = new StringBuilder();
			nsb.append(location.getSystemId());
            CellIDInfo info = new CellIDInfo();
            info.cellId = cellIDs;
            info.locationAreaCode = networkID; //ok
            info.mobileNetworkCode = nsb.toString();
            info.mobileCountryCode = tm.getNetworkOperator().substring(0, 3);
            info.radioType = "cdma";
            CellID.add(info);
		}
		//移动2G卡 + CMCC + 2 
		//type = NETWORK_TYPE_EDGE
		else if(type == TelephonyManager.NETWORK_TYPE_EDGE)
		{
			GsmCellLocation location = (GsmCellLocation)tm.getCellLocation();  
			int cellIDs = location.getCid();  
			int lac = location.getLac(); 
			CellIDInfo info = new CellIDInfo();
            info.cellId = cellIDs;
            info.locationAreaCode = lac;
            info.mobileNetworkCode = tm.getNetworkOperator().substring(3, 5);   
            info.mobileCountryCode = tm.getNetworkOperator().substring(0, 3);
            info.radioType = "gsm";
            CellID.add(info);
		}
		//联通的2G经过测试 China Unicom   1 NETWORK_TYPE_GPRS
		else if(type == TelephonyManager.NETWORK_TYPE_GPRS)
		{
			GsmCellLocation location = (GsmCellLocation)tm.getCellLocation();  
			int cellIDs = location.getCid();  
			int lac = location.getLac(); 
			CellIDInfo info = new CellIDInfo();
            info.cellId = cellIDs;
            info.locationAreaCode = lac;
            //经过测试，获取联通数据以下两行必须去掉，否则会出现错误，错误类型为JSON Parsing Error
            //info.mobileNetworkCode = tm.getNetworkOperator().substring(3, 5);   
            //info.mobileCountryCode = tm.getNetworkOperator().substring(0, 3);
            info.radioType = "gsm";
            CellID.add(info);
		}
		else if(type == TelephonyManager.NETWORK_TYPE_HSUPA){
			Log.e(TAG, "TelephonyManager.NETWORK_TYPE_HSUPA");

			GsmCellLocation location = (GsmCellLocation)tm.getCellLocation();  
			int cellIDs = location.getCid();  
			int lac = location.getLac(); 
			CellIDInfo info = new CellIDInfo();
            info.cellId = cellIDs;
            info.locationAreaCode = lac;
            info.mobileNetworkCode = tm.getNetworkOperator().substring(3, 5);   
            info.mobileCountryCode = tm.getNetworkOperator().substring(0, 3);
            info.radioType = "gsm";
            CellID.add(info);
			
			
			
//
//            GsmCellLocation gcl = (GsmCellLocation) tm.getCellLocation();
//            if (gcl == null) {
//                return null;
//            }
//            int cid = gcl.getCid();
//            int lac = gcl.getLac();
//            int mcc = Integer.valueOf(tm.getNetworkOperator().substring(0, 3));
//            int mnc = Integer.valueOf(tm.getNetworkOperator().substring(3, 5));
//            try {
//                // 组装JSON查询字符串
//                JSONObject holder = new JSONObject();
//                holder.put("version", "1.1.0");
//                holder.put("host", "maps.google.com");
//                holder.put("address_language", "zh_CN");
//                holder.put("request_address", true);
//
//                JSONArray array = new JSONArray();
//                JSONObject data = new JSONObject();
//                data.put("cell_id", cid); // 25070
//                data.put("location_area_code", lac);// 4474
//                data.put("mobile_country_code", mcc);// 460
//                data.put("mobile_network_code", mnc);// 0
//                data.put("radio_type","gsm");
//                array.put(data);
//                holder.put("cell_towers", array);
//
//                // 创建连接，发送请求并接受回应
//                DefaultHttpClient client = new DefaultHttpClient();
//
//                String host=Proxy.getDefaultHost();
//                HttpPost post = new HttpPost("http://www.google.com/loc/json");
//                if (host!=null) {
//                    int port = Proxy.getDefaultPort();
//                    HttpHost httpHost=new HttpHost(host, port);
//                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost);
//                }
//
//                StringEntity se = new StringEntity(holder.toString());
//                post.setEntity(se);
//                HttpResponse resp = client.execute(post);
//                HttpEntity entity = resp.getEntity();
//                InputStream is = entity.getContent();
//                if (is == null) {
//                    return null;
//                }
//                BufferedReader in = new BufferedReader(new InputStreamReader(is));
//                StringBuffer buffer = new StringBuffer();
//                String line = "";
//                while ((line = in.readLine()) != null){
//                  buffer.append(line);
//                }
//                Log.e(TAG, "buffer.toString():" + buffer.toString());
//
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//	        
		}
		else if(type == TelephonyManager.NETWORK_TYPE_HSDPA){
			Log.e(TAG, "TelephonyManager.NETWORK_TYPE_HSDPA");
		}
		else {
//			tv.setText("Current Not Support This Type.");
		}

		return transResponse(execute(doApn(CellID)));
	}
	
	public MLocation doGpsPost(double lat, double lng) throws Exception {
		return transResponse(execute(doGps(lat, lng)));
	}

	private MLocation transResponse(HttpResponse response) {
		MLocation location = null;
		if (response.getStatusLine().getStatusCode() == 200) {
			location = new MLocation();
			HttpEntity entity = response.getEntity();
			BufferedReader br;
			try {
				br = new BufferedReader(new InputStreamReader(
						entity.getContent()));
				StringBuffer sb = new StringBuffer();
				String result = br.readLine();
				Log.e(TAG, "result:"+result);
				while (result != null) {
					sb.append(result);
					result = br.readLine();
				}
				JSONObject json = new JSONObject(sb.toString());
				JSONObject lca = json.getJSONObject("location");

				location.Access_token = json.getString("access_token");
				if (lca != null) {
					if(lca.has("accuracy"))
						location.Accuracy = lca.getString("accuracy");
					if(lca.has("longitude"))
						location.Latitude = lca.getDouble("longitude");
					if(lca.has("latitude"))
						location.Longitude = lca.getDouble("latitude");
					if(lca.has("address")) {
						JSONObject address = lca.getJSONObject("address");
						if (address != null) {
							if(address.has("region"))
								location.Region = address.getString("region");
							if(address.has("street_number"))
								location.Street_number = address
										.getString("street_number");
							if(address.has("country_code"))
								location.Country_code = address
										.getString("country_code");
							if(address.has("street"))
								location.Street = address.getString("street");
							if(address.has("city"))
								location.City = address.getString("city");
							if(address.has("country"))
								location.Country = address.getString("country");
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				location = null;
			}
		}
		return location;
	}

	private JSONObject doGps(double lat, double lng) throws Exception {
		JSONObject holder = new JSONObject();
		holder.put("version", "1.1.0");
		holder.put("host", "maps.google.com");
		holder.put("address_language", "zh_CN");
		holder.put("request_address", true);
		
		JSONObject data = new JSONObject();
		data.put("latitude", lat);
		data.put("longitude", lng);
		holder.put("location", data);

		return holder;
	}
	
	private JSONObject doApn(ArrayList<CellIDInfo> cellID) throws Exception {
		JSONObject holder = new JSONObject();
		holder.put("version", "1.1.0");
		holder.put("host", "maps.google.com");
		holder.put("home_mobile_country_code", cellID.get(0).mobileCountryCode);
		holder.put("home_mobile_network_code", cellID.get(0).mobileNetworkCode);
		holder.put("radio_type", cellID.get(0).radioType);
		holder.put("request_address", true);
		if ("460".equals(cellID.get(0).mobileCountryCode)) 
			holder.put("address_language", "zh_CN");
		else
			holder.put("address_language", "en_US");
		JSONObject data,current_data;
		JSONArray array = new JSONArray();
		current_data = new JSONObject();
		current_data.put("cell_id", cellID.get(0).cellId);
		current_data.put("location_area_code", cellID.get(0).locationAreaCode);
		current_data.put("mobile_country_code", cellID.get(0).mobileCountryCode);
		current_data.put("mobile_network_code", cellID.get(0).mobileNetworkCode);
		current_data.put("age", 0);
		array.put(current_data);
		if (cellID.size() > 2) {
			for (int i = 1; i < cellID.size(); i++) {
				data = new JSONObject();
				data.put("cell_id", cellID.get(i).cellId);
				data.put("location_area_code", cellID.get(i).locationAreaCode);
				data.put("mobile_country_code", cellID.get(i).mobileCountryCode);
				data.put("mobile_network_code", cellID.get(i).mobileNetworkCode);
				data.put("age", 0);
				array.put(data);
			}
		}
		holder.put("cell_towers", array);
		Log.e(TAG, "holder.toString():" + holder.toString());
		return holder;
	}
	
	private JSONObject doWifi() throws Exception {
		JSONObject holder = new JSONObject();
		holder.put("version", "1.1.0");
		holder.put("host", "maps.google.com");
		holder.put("address_language", "zh_CN");
		holder.put("request_address", true);
		
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		
		if(wifiManager.getConnectionInfo().getBSSID() == null) {
			throw new RuntimeException("bssid is null");
		}
		
		JSONArray array = new JSONArray();
		JSONObject data = new JSONObject();
		data.put("mac_address", wifiManager.getConnectionInfo().getBSSID());  
        data.put("signal_strength", 8);  
        data.put("age", 0);  
		array.put(data);
		holder.put("wifi_towers", array);
		
		return holder;
	}

	public static class MLocation {
		public String Access_token;

		public double Latitude;

		public double Longitude;

		public String Accuracy;

		public String Region;

		public String Street_number;

		public String Country_code;

		public String Street;

		public String City;

		public String Country;

		@Override
		public String toString() {
			StringBuffer buffer = new StringBuffer();
			buffer.append("Access_token:" + Access_token + "\n");
			buffer.append("Region:" + Region + "\n");
			buffer.append("Accuracy:" + Accuracy + "\n");
			buffer.append("Latitude:" + Latitude + "\n");
			buffer.append("Longitude:" + Longitude + "\n");
			buffer.append("Country_code:" + Country_code + "\n");
			buffer.append("Country:" + Country + "\n");
			buffer.append("City:" + City + "\n");
			buffer.append("Street:" + Street + "\n");
			buffer.append("Street_number:" + Street_number + "\n");
			return buffer.toString();
		}
	}
}
